package com.will.txj.common.utils;


import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

/**
 * @author: wen-yi;
 * @date: 2021/12/4 17:04;
 * @Description: 图片预览地址 + 验证码 使用
 */
public class AESCrypt {

    private SecretKeySpec secretKeySpec = null;
    public static final String module = AESCrypt.class.getName();
    private static final String NOW_KEY = "d084fda59e8740ce998a93d42d34e335";        //当前使用的密钥

    /**
     * Creates a new AESCrypt object.
     *
     * @param secretKeySpec A SecretKeySpec object.
     */
    public AESCrypt(SecretKeySpec secretKeySpec) {
        this.secretKeySpec = secretKeySpec;
    }

    /**
     * Creates a new AESCrypt object.
     *
     * @param key An encoded secret key
     */
    public AESCrypt(byte[] key) {
        try {
            secretKeySpec = new SecretKeySpec(key, "AES");
        } catch (Exception e) {
        }
    }

    /**
     * Creates a new AESCrypt object.
     *
     * @param keyFile A file object containing the secret key as a String object.
     */
    public AESCrypt(File keyFile) {
        try {
            FileInputStream is = new FileInputStream(keyFile);
            ObjectInputStream os = new ObjectInputStream(is);
            String keyString = (String) os.readObject();

            is.close();

            byte[] keyBytes = keyString.getBytes();

            secretKeySpec = new SecretKeySpec(keyBytes, "AES");
        } catch (Exception e) {
        }
    }

    /**
     * Encrypt the string with the secret key.
     *
     * @param string The string to encrypt.
     */
    public byte[] encrypt(String string) {
        return encrypt(string.getBytes());
    }

    /**
     * Decrypt the string with the secret key.
     *
     * @param string The string to decrypt.
     */
    public byte[] decrypt(String string) {
        return decrypt(string.getBytes());
    }

    /**
     * Encrypt the byte array with the secret key.
     *
     * @param bytes The array of bytes to encrypt.
     */
    public byte[] encrypt(byte[] bytes) {
        byte[] resp = null;

        try {
            resp = crypt(bytes, Cipher.ENCRYPT_MODE);
        } catch (Exception e) {
            return null;
        }
        return resp;
    }

    /**
     * Decrypt the byte array with the secret key.
     *
     * @param bytes The array of bytes to decrypt.
     */
    public byte[] decrypt(byte[] bytes) {
        byte[] resp = null;

        try {
            resp = crypt(bytes, Cipher.DECRYPT_MODE);
        } catch (Exception e) {
//        	Debug.logInfo(e.getMessage(),module);
            return null;
        }
        return resp;
    }

    private byte[] crypt(byte[] bytes, int mode) throws Exception {
        if (secretKeySpec == null)
            throw new Exception("SecretKey cannot be null.");
        Cipher cipher = Cipher.getInstance("AES");

        cipher.init(mode, secretKeySpec);
        return cipher.doFinal(bytes);
    }

    public static byte[] generateKey() throws NoSuchAlgorithmException {
        KeyGenerator keyGen = KeyGenerator.getInstance("AES");
        keyGen.init(128);

        SecretKey secretKey = keyGen.generateKey();
        byte[] keyBytes = secretKey.getEncoded();

        return keyBytes;
    }

    /**
     * 使用AES128加密算法进行加密
     *
     * @param str
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static String encryptByAES(String str) throws Exception {
        AESCrypt c = new AESCrypt(StringUtil.fromHexString(NOW_KEY));
        return StringUtil.toHexString(c.encrypt(str));
    }

    /**
     * 使用AES128加密算法进行加密
     *
     * @param str
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static String encrypt(String str,String key) throws Exception {
        AESCrypt c = new AESCrypt(StringUtil.fromHexString(key));
        return StringUtil.toHexString(c.encrypt(str));
    }

    /**
     * 使用AES128加密算法进行解密
     *
     * @param str
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static String decryptByAES(String str) throws Exception {
        AESCrypt c = new AESCrypt(StringUtil.fromHexString(NOW_KEY));
        byte[] decryptedBytes = c.decrypt(StringUtil.fromHexString(str));
        return new String(decryptedBytes);
    }

    /**
     * 使用AES128加密算法进行解密
     *
     * @param str
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static String decrypt(String str,String key) throws Exception {
        AESCrypt c = new AESCrypt(StringUtil.fromHexString(key));
        byte[] decryptedBytes = c.decrypt(StringUtil.fromHexString(str));
        return new String(decryptedBytes);
    }

    public static String makePassword(String pwdchars, int pwdlen) {
        String tmpstr = "";
        int iRandNum;
        Random rnd = new Random();
        for (int i = 0; i < pwdlen; i++) {
            iRandNum = rnd.nextInt(pwdchars.length());
            tmpstr += pwdchars.charAt(iRandNum);
        }
        return tmpstr;
    }

    public static void main(String args[]) throws Exception {
        String admin = "admin";
        String key = "d084fda59e8740ce998a93d42d34e335";
        System.out.println("原文："+admin);
        System.out.println("密钥："+key);
        String s = encryptByAES(admin);
        System.out.println("加密："+s);
        System.out.println("解密："+decryptByAES(s));
        // 8386644f3528f659c734fd0388b1fa52

        String text = "id=11";
        System.out.println(encrypt(text,"d084fda59e8740ce948a93d12d64e617"));
    }
}


